package com.team.admin.auth;

import com.alibaba.fastjson.JSONObject;
import com.team.admin.domain.SystemUser;
import com.team.admin.service.AuthExceptionService;
import com.team.admin.service.AuthenticationJwtService;
import com.team.common.result.R;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class CustomerAuthResponseHandler {

    @Autowired
    private AuthExceptionService authExceptionService;

    @Autowired
    private AuthenticationJwtService authenticationJwtService;


    private final static String DEFAULT_CONTENT_TYPE = "application/json; charset=utf-8";

    public void responseResult(HttpServletResponse httpServletResponse,
                               AccessDeniedException e) throws IOException {
        ExceptionCode code
                = authExceptionService.accessDeniedExceptionResult(e);
        defaultResponse(httpServletResponse,code);
    }


    public void successfulAuthentication(SystemUser systemUser,HttpServletResponse response) throws IOException {
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(DEFAULT_CONTENT_TYPE);
        response.getWriter()
                .write(authenticationJwtService.createJWT(systemUser));
    }

    private void defaultResponse(HttpServletResponse httpServletResponse,ExceptionCode code)throws IOException{
        httpServletResponse.setCharacterEncoding(StandardCharsets.UTF_8.name());
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setContentType(DEFAULT_CONTENT_TYPE);
        if(code.getStatus() != null && code.getStatus().value() != HttpStatus.OK.value()){
            httpServletResponse.setStatus(code.getStatus().value());
        }
        httpServletResponse.getWriter()
                .write(cover(code));
    }

    public void authenticationResult(HttpServletResponse httpServletResponse,
                                     AuthenticationException e) throws IOException {
        ExceptionCode code
                = authExceptionService.authenticationExceptionResult(e);
        defaultResponse(httpServletResponse,code);
    }



    private String cover(ExceptionCode e){
        R r = R.fail(e.message,e.code);
        return JSONObject.toJSONString(r);
    }


    @Data
    public static class ExceptionCode{

        private HttpStatus status;

        private String message;

        private String code;

    }
}
